<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            padding: 0;
            margin: 0;
        }
        body{
            background-color: grey;
        }
        .square{
            width: 200px;
            height: 200px;
            background-color: green;
            position: absolute;
            transform: translateX(50%) translateY(50%);
            border-radius: 50%;
        }
    </style>
</head>
<body>
    <button class="up" onclick="moveup(square);">向上</button>
    <button class="down"onclick="moveTop(square);" >向下</button>
    <button class="left" onclick="moveLeft(square);">向左</button>
    <button class="right" onclick="moveRight(square);">向右</button>
    <div class="square"></div>
</body>
<script>
    const up = document.querySelector('.up');
    const down = document.querySelector('.down');
    const left  = document.querySelector('.left');
    const right = document.querySelector('.right');
    const square = document.querySelector('.square');

    let step =0; 

    // 封装动画
    function moveLeft(obj){
        obj.timer =setInterval(function(){
            //停止条件 控制时长
            if(step<50){
                step = step + 5;
            } 
            //执行完一次之后 清理定时器 step=0 之后 再次点击方可重新进入
            else{
                clearInterval(obj.timer);
                step=0;
            }
             obj.style.left = obj.offsetLeft +10+'px';
             console.log(step);
        },15)
    }

    function moveRight(obj,target){
        obj.timer =setInterval(function(){
            if(step<100){
                step = step + 5;
            } 
            else{
                clearInterval(obj.timer);
                step=0;
            }
                obj.style.left = obj.offsetLeft -10+ 'px';
        },15)
    }
    function moveTop(obj,target){
        obj.timer=setInterval(function(){
            if(step<100){
                step = step + 5;
            } 
            else{
                clearInterval(obj.timer);
                step=0;
            }
                obj.style.top = obj.offsetTop +10+ 'px';
        },15)
    }
    function moveup(obj,target){
        obj.timer =setInterval(function(){
            if(step<100){
                step = step + 5;
            } 
            else{
                clearInterval(obj.timer);
                step=0;
            }
               obj.style.top = obj.offsetTop -10+ 'px';
        },15)
    }
</script>
</html>